import 'package:flutter/material.dart';
import 'package:journal/blocs/authentication_bloc.dart';
import 'package:journal/blocs/authentication_bloc_provider.dart';
import 'package:journal/blocs/home_bloc.dart';
import 'package:journal/blocs/home_bloc_provider.dart';
import 'package:journal/services/authentication.dart';
import 'package:journal/services/db_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:journal/pages/home.dart';
import 'package:journal/pages/login.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
// await Firebase.initializeApp();
  runApp(MyApp());
}

// Future<void> main()  async{
//   WidgetsFlutterBinding.ensureInitialized();
//   runApp(const MyApp());
// }

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  // const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {

    final Future<FirebaseApp> _initialization = Firebase.initializeApp(
        name: 'journal',
        options: const FirebaseOptions(
            appId: '1:896642007977:android:e49db2a892cf4fc446bab8',
            apiKey: 'AIzaSyDb_k5lLRceMU47LBPNun5kD7ndm2vSJkQ',
            messagingSenderId: '896642007977',
            projectId: 'journal-8b614'
        )
    );

    AuthenticationService _authenticationService;

    return FutureBuilder(
      future: _initialization,
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          return Container(
            color: Colors.lightGreen,
            child: CircularProgressIndicator(),
          );
        }

        // Once complete, show your application
        if (snapshot.connectionState == ConnectionState.done) {
          print("oncreate snapshot=$snapshot");
          AuthenticationService.app = snapshot.data as FirebaseApp;
          DbFirestoreService.app = snapshot.data as FirebaseApp;
          _authenticationService = AuthenticationService();
          final AuthenticationBloc _authenticationBloc = AuthenticationBloc(_authenticationService);
          // return Container(
          //   color: Colors.blue,
          //   child: CircularProgressIndicator(),
          // );
          return AuthenticationBlocProvider(
            authenticationBloc: _authenticationBloc,
            child: StreamBuilder(
              initialData: null,
              stream: _authenticationBloc.user,
              builder: (BuildContext context, AsyncSnapshot usersnap) {
                if (usersnap.connectionState == ConnectionState.waiting) {
                  return Container(
                    color: Colors.blue,
                    child: CircularProgressIndicator(),
                  );
                } else if (usersnap.hasData && usersnap.data != "") {
                  // return Container(
                  //   color: Colors.red,
                  //   child: CircularProgressIndicator(),
                  // );
                  // var user = _authenticationService.getFirebaseAuth().currentUser;
                  // user?.uid = usersnap.data;
                  // HomeBloc.user = user;
                  AuthenticationService.uid = usersnap.data;
                  print("StreamBuilder snapshot=${usersnap.data}");
                  return HomeBlocProvider(
                    homeBloc: HomeBloc(DbFirestoreService(), _authenticationService), // Inject the DbFirestoreService() & AuthenticationService()
                    uid: usersnap.data,
                    child: _buildMaterialApp(Home()),
                  );
                } else {
                  return _buildMaterialApp(Login());
                }
              },
            ),
          );
        }

        // Otherwise, show something whilst waiting for initialization to complete
        // return _buildMaterialApp(Login());
        return Container(
          color: Colors.red,
          child: CircularProgressIndicator(),
        );
      },
    );
    // return AuthenticationBlocProvider(
    //   authenticationBloc: _authenticationBloc,
    //   child: StreamBuilder(
    //     initialData: null,
    //     stream: _authenticationBloc.user,
    //     builder: (BuildContext context, AsyncSnapshot snapshot) {
    //       if (snapshot.connectionState == ConnectionState.waiting) {
    //         return Container(
    //           color: Colors.lightGreen,
    //           child: CircularProgressIndicator(),
    //         );
    //       } else if (snapshot.hasData) {
    //         return HomeBlocProvider(
    //           homeBloc: HomeBloc(DbFirestoreService(), _authenticationService), // Inject the DbFirestoreService() & AuthenticationService()
    //           uid: snapshot.data,
    //           child: _buildMaterialApp(Home()),
    //         );
    //       } else {
    //         return _buildMaterialApp(Login());
    //       }
    //     },
    //   ),
    // );
  }

  MaterialApp _buildMaterialApp(Widget homePage) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Journal',
      theme: ThemeData(
        primarySwatch: Colors.lightGreen,
        canvasColor: Colors.lightGreen.shade50,
        bottomAppBarColor: Colors.lightGreen,
      ),
      home: homePage,
    );
  }
}